package impl;

import java.util.Date;
import java.util.List;

import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.logging.Logger;

import p3_entities.LindenBet;
import p3_entities.LotteryGame;

import api.ejb.IGameEngine;



/**
 * Session Bean implementation class GameEngine
 */
@Singleton(name="IGameEngine")
//@TransactionAttribute(value=TransactionAttributeType.REQUIRES_NEW)
@WebService(endpointInterface="api.ejb.IGameEngine",serviceName="LotteryWS")
public class GameEngine implements IGameEngine {

	@PersistenceContext(unitName="LotteryGamePU")
	EntityManager em;
	
	private static int MIN = 1;
	private static int MAX = 100;

	private static final Logger log = Logger.getLogger(GameEngine.class);

    /**
     * Default constructor. 
     */
    public GameEngine() {
    }

	@Override
	public boolean makeBet(int sourceAppId, int betNumber, int betAmount,
			int gamblerId, int gameId) {

		log.info("Executing ---------->");
		
		LotteryGame game = em.find(LotteryGame.class, gameId);		
		
		if(game == null)
			return false;
		
		LindenBet bet = new LindenBet();
		bet.setAppId(sourceAppId);
		bet.setBetNumber(betNumber);
		bet.setLindenEuros(betAmount);
		bet.setLotteryGame(game);
		bet.setUserId(gamblerId);
		em.persist(bet);
		
//		throw new RuntimeException();
		log.info("<--------------- Done");

		
		return true;
	}


	@Override
	public List<LindenBet> getWinnerList(int sourceAppId) {
		
		log.info("Executing ---------->");
		
		Query q = em.createNamedQuery("getLotteryAppWinners");
		q.setParameter(1, sourceAppId);
		
		List<LindenBet> winners = q.getResultList();
		
		log.info("There are "+ winners.size()+" winners");

		
		log.info("<--------------- Done");

		
		return winners;
	}
	
	@Schedule(minute="*/1", hour="*", persistent=false)
	private void genWinnerNumber() {
		try {
			log.info("Executing ---------->");

			Query query=em.createNamedQuery("getAvailableLotteries");
			
			LotteryGame game = (LotteryGame) query.getSingleResult();		
			
			if (game.getDrawDay().before(new Date())) {
				int number = MIN + (int)(Math.random() * ((MAX - MIN) + 1));
				game.setDrawnNumber(number);
				em.persist(game);
			}
			
		
		} catch (NoResultException e) {
			log.warn("No lotteries available to generate");
			
		}
		
		log.info("<--------------- Done");

	}

	@Override
	public LotteryGame getActiveLottery() {
		
		log.info("Executing ---------->");

		Query query=em.createNamedQuery("getAvailableLotteries");

		List<LotteryGame> games = query.getResultList();
		LotteryGame game = null;
		if (games.size() == 0){
			game=null;
			log.info("*No active lottery*");
		}
		else {
			game = (LotteryGame) query.getSingleResult();
		}
		log.info("<--------------- Done");

		
		return game;
	}
	
	

}
